package com.ruoyi.system.controller;

import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.system.controller.es.EsUnService;
import com.ruoyi.system.controller.es.dto.EsSearch;
import com.ruoyi.system.domain.FyData;
import com.ruoyi.system.domain.FyPeople;
import com.ruoyi.system.domain.vo.DeleteIdVo;
import com.ruoyi.system.domain.vo.NewProjectTemplateVo;
import com.ruoyi.system.domain.vo.ProjectPeopleTemplateVo;
import com.ruoyi.system.domain.vo.ProjectTemplateVo;
import com.ruoyi.system.service.IFyDataService;
import com.ruoyi.system.service.IFyPeopleService;
import com.ruoyi.system.util.UniqueIdGenerator;
import org.apache.commons.math3.stat.descriptive.summary.Product;
import org.apache.velocity.runtime.directive.Break;
import org.apache.velocity.runtime.directive.contrib.For;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.FyProject;
import com.ruoyi.system.service.IFyProjectService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 项目Controller
 *
 * @author ruoyi
 * @date 2025-06-05
 */
@RestController
@RequestMapping("/system/project")
public class FyProjectController extends BaseController
{
    @Autowired
    private IFyProjectService fyProjectService;
    @Autowired
    private IFyDataService fyDataService;
    @Autowired
    private IFyPeopleService fyPeopleService;
    @Autowired
    private EsUnService esUnService;
    @Autowired
    private RedisCache redisCache;
    /**
     * 查询项目列表
     */
//    @PreAuthorize("@ss.hasPermi('system:project:list')")
    @GetMapping("/list")
    public TableDataInfo list(FyProject fyProject)
    {
        startPage();
        List<FyProject> list = fyProjectService.selectFyProjectList(fyProject);
        return getDataTable(list);
    }



    /**
     * 资料模版
     */
    @Log(title = "资料", businessType = BusinessType.EXPORT)
    @GetMapping("/templatedata")
    public void templatedata(HttpServletResponse response, FyData fyData)
    {
        List<FyData> list = new ArrayList<>();
        ExcelUtil<FyData> util = new ExcelUtil<FyData>(FyData.class);
        util.exportExcel(response, list, "资料数据");
    }
    /**
     * 查询当前项目下的传承人
     */

    /**
     * 导出项目列表
     */
    @PreAuthorize("@ss.hasPermi('system:project:export')")
    @Log(title = "项目", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, FyProject fyProject)
    {
        List<FyProject> list = fyProjectService.selectFyProjectList(fyProject);
        ExcelUtil<FyProject> util = new ExcelUtil<FyProject>(FyProject.class);
        util.exportExcel(response, list, "项目数据");
    }

    /**
     * 获取项目详细信息
     */
//    @PreAuthorize("@ss.hasPermi('system:project:query')")
    @GetMapping(value = "getInfo")
    public AjaxResult getInfo(Long projectId)
    {
        return success(fyProjectService.selectFyProjectByProjectId(projectId));
    }

    /**
     * 新增项目
     */
//    @PreAuthorize("@ss.hasPermi('system:project:add')")
    @Log(title = "项目", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody FyProject fyProject)
    {
        List<FyProject> list = fyProjectService.selectFyProjectList2(fyProject);
        if (StringUtils.isNotEmpty(list)){
            return AjaxResult.error("项目已存在");
        }
        fyProject.setProjectId(Long.valueOf(DateUtils.dateTimeNow()));
//        redisCache.deleteObject("home:count");
        EsSearch esSearch=new EsSearch();
        esSearch.setId(fyProject.getProjectId());
        esSearch.setLanmu("资源-项目名录");
        esSearch.setLanmuId(1);
        esSearch.setTitle(fyProject.getProjectName());
        esSearch.setContent(fyProject.getProjectBrief());
        esUnService.save(esSearch);
        return toAjax(fyProjectService.insertFyProject(fyProject));
    }

    /**
     * 修改项目
     */
//    @PreAuthorize("@ss.hasPermi('system:project:edit')")
    @Log(title = "项目", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    public AjaxResult edit(@RequestBody FyProject fyProject)
    {
        EsSearch esSearch=new EsSearch();
        esSearch.setId(fyProject.getProjectId());
        esSearch.setLanmu("资源-项目名录");
        esSearch.setLanmuId(1);
        esUnService.delete(esSearch);
        esSearch.setTitle(fyProject.getProjectName());
        esSearch.setContent(fyProject.getProjectBrief());
        esUnService.save(esSearch);
        return toAjax(fyProjectService.updateFyProject(fyProject));
    }

    /**
     * 删除项目
     */
//    @PreAuthorize("@ss.hasPermi('system:project:remove')")
    @Log(title = "项目", businessType = BusinessType.DELETE)
	@PostMapping("/remove")
    public AjaxResult remove(@RequestBody DeleteIdVo projectIds)
    {
//        redisCache.deleteObject("home:count");


        return toAjax(fyProjectService.deleteFyProjectByProjectIds(projectIds.getProjectIds()));
    }


    /**
     * 下载项目模版
     * @param response
     * @throws UnsupportedEncodingException
     */
    @GetMapping("/template")
    @Log(title = "项目", businessType = BusinessType.EXPORT)
    public void template(HttpServletResponse response) throws UnsupportedEncodingException {
        List<ProjectTemplateVo> list = new ArrayList<>();
        ProjectTemplateVo projectTemplateVo=new ProjectTemplateVo();
        projectTemplateVo.setProjectName("项目名称xxx");
        projectTemplateVo.setProjectType("传统技艺");
        projectTemplateVo.setProjectLevel("市级");
        projectTemplateVo.setProjectBatch("2025年第一批");
        projectTemplateVo.setIsTop("是");
        projectTemplateVo.setProjectBrief("项目描述");
        projectTemplateVo.setUnit("朝阳");
        projectTemplateVo.setRemake("此行测试数据不做统计，上传时请删除");
                list.add(projectTemplateVo);
        ExcelUtil<ProjectTemplateVo> util = new ExcelUtil<ProjectTemplateVo>(ProjectTemplateVo.class);
        String fileName = URLEncoder.encode("项目上传模版" + ".xlsx", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        util.exportExcel(response, list, "项目上传模版");
    }

//    @Log(title = "项目管理", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    @Transactional
    public AjaxResult importData(MultipartFile file) throws Exception
    {
        ExcelUtil<ProjectTemplateVo> util = new ExcelUtil<ProjectTemplateVo>(ProjectTemplateVo.class);
        List<ProjectTemplateVo> voList = util.importExcel(file.getInputStream());
        boolean abc=true;
        for(ProjectTemplateVo l:voList){
            FyProject fyProject=new FyProject();
            BeanUtils.copyBeanProp(fyProject,l);
            List<FyProject> list = fyProjectService.selectFyProjectList2(fyProject);
            if (StringUtils.isNotEmpty(list)){
                abc=false;
                break;
            }
        }

        if (abc==false){
            return AjaxResult.error("上传数据中存在重复项目");
        }
            voList.stream().forEach(l->{
                FyProject fyProject=new FyProject();

                BeanUtils.copyBeanProp(fyProject,l);
                fyProjectService.insertFyProject(fyProject);
            });

        return AjaxResult.success();
    }
    /**
     * 下载项目模版 传承人
     * @param response
     * @throws UnsupportedEncodingException
     */
    @GetMapping("/templatepeople")
    @Log(title = "项目", businessType = BusinessType.EXPORT)
    public void templatepeople(HttpServletResponse response) throws UnsupportedEncodingException {
        List<ProjectPeopleTemplateVo> list = new ArrayList<>();
        ProjectPeopleTemplateVo projectTemplateVo=new ProjectPeopleTemplateVo();
        projectTemplateVo.setPeopleName("张三");
        projectTemplateVo.setPeopleBirth("1991年三月1日");
        projectTemplateVo.setPeopleSex("男");
        projectTemplateVo.setPeopleMz("汉");
        projectTemplateVo.setProjectName("传统器乐");
        projectTemplateVo.setPeopleBrief("传承人介绍");
        list.add(projectTemplateVo);
        ExcelUtil<ProjectPeopleTemplateVo> util = new ExcelUtil<ProjectPeopleTemplateVo>(ProjectPeopleTemplateVo.class);
        String fileName = URLEncoder.encode("项目添加传承人上传模版" + ".xlsx", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        util.exportExcel(response, list, "项目添加传承人上传模版");
    }
    @PostMapping("/importDatapeople")
    @Transactional
    public AjaxResult importDatapeople(MultipartFile file) throws Exception
    {
        ExcelUtil<ProjectPeopleTemplateVo> util = new ExcelUtil<ProjectPeopleTemplateVo>(ProjectPeopleTemplateVo.class);
        List<ProjectPeopleTemplateVo> voList = util.importExcel(file.getInputStream());
        for(ProjectPeopleTemplateVo l:voList){
            FyPeople fyPeople=new FyPeople();
            BeanUtils.copyBeanProp(fyPeople,l);
            List<FyPeople> list = fyPeopleService.selectFyPeopleList(fyPeople);
            FyProject project=new FyProject();
            project.setProjectName(l.getProjectName());
            List<FyProject> list2 = fyProjectService.selectFyProjectList2(project);
            fyPeople.setProjectId(list2.get(0).getProjectId());
            if (StringUtils.isEmpty(list)){
                fyPeopleService.insertFyPeople(fyPeople);
            }

        }
        return AjaxResult.success();
    }
    Long i=1l;
    @PostMapping("/projectimport")
    @Transactional
    public AjaxResult projectimport(MultipartFile file) throws Exception
    {

        ExcelUtil<NewProjectTemplateVo> util = new ExcelUtil<NewProjectTemplateVo>(NewProjectTemplateVo.class);
        List<NewProjectTemplateVo> voList = util.importExcel(file.getInputStream(),4);

        Map<String, List<NewProjectTemplateVo>> listMap = voList.stream()
                .collect(Collectors.groupingBy(NewProjectTemplateVo::getProjectName));
        listMap.forEach((key, value) -> {
            //项目
            FyProject project=new FyProject();
            project.setProjectName(value.get(0).getProjectName());
            List<FyProject> list = fyProjectService.selectFyProjectList2(project);
            if (StringUtils.isEmpty(list)){
                project.setProjectId(i);
                project.setProjectType(value.get(0).getProjectType());
                project.setProjectLevel(value.get(0).getProjectLevel());
                project.setProjectBatch(value.get(0).getProjectBatch());
                project.setProjectBrief(value.get(0).getProjectBrief());
                project.setUnit(value.get(0).getUnit());
                fyProjectService.insertFyProject(project);
            }
            //传承人
            FyPeople people=new FyPeople();
            people.setPeopleName(value.get(0).getPeopleName());
            people.setPeopleCode(value.get(0).getPeople());
            people.setPeopleBirth(value.get(0).getPeopleBirth());
            people.setPeopleMz(value.get(0).getPeopleMz());
            people.setPeopleSex(value.get(0).getPeopleSex());
            List<FyPeople> peoplelist = fyPeopleService.selectFyPeopleList(people);
            people.setProjectId(i);
            people.setPeopleId(i);
            if (StringUtils.isEmpty(peoplelist)){
                fyPeopleService.insertFyPeople(people);
            }

            value.stream().forEach(v->{
                //资源
                FyData data=new FyData();
                data.setProjectId(i);
                data.setPeopleId(i);
                data.setPeopleCode(v.getPeopleCode());
                data.setDataName(v.getDataName());

                data.setDataType(Long.valueOf(v.getDataType().replaceAll("学术文献","3").replaceAll("图片","1").replaceAll("音视频","2").replaceAll("文本","3")));
                data.setDataFormat(v.getDataFormat());
                data.setJibie(v.getJibie());
                data.setJigou(v.getJigou());
                data.setProjectName(v.getProjectName());
                data.setZhuluPeople(v.getZhuluPeople());
                data.setZhuluTime("2021年2月20日");
                data.setDataUrl("https://xunli-chaoyangfy.oss-cn-beijing.aliyuncs.com/chaoyangfy20250711/"+
                        v.getDataType().replaceAll("学术文献","文献").replaceAll("图片","图片").replaceAll("音视频","影音").replaceAll("文本","文献")+
                        "/"+v.getPeopleCode()+"."+v.getDataFormat());
                fyDataService.insertFyData(data);

            });

            i+=1;
        });

        return AjaxResult.success(listMap);
    }


}
